/**
 * Created by imouze on 2017-10-17.
 */
const koa = require('koa');
const app = new koa();
const bodyParser = require('koa-bodyparser');
const controller = require('./controller');
const views = require('koa-views');
const logger = require('koa-logger');
// const isProduction = process.env.NODE_ENV === 'production';
const staticFiles = require('./static-file');
const xxsfilter = require('./middleware/xxsfilter');
const koaOnerror = require('koa-onerror');

// 记录浏览器信息，或者跳转WAP还是PC
app.use(async (ctx, next) => {
    
    console.log(ctx.headers['user-agent']);
    
    await next();
});

// bodyParser一定要放在router前面，否则无法解析
app.use(bodyParser());

// log request URL:
app.use(async (ctx, next) => {
    const start = Date.now();
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    await next();
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
app.use(logger());
// XXSFilter
app.use(xxsfilter());
// 设置静态文件地址路径
app.use(require('koa-static')(__dirname + '/static'));
// 设置模板路径和模板引擎
app.use(views(__dirname + '/views', {map: {html: 'nunjucks'}}));

koaOnerror(app, {
    template: 'views/500.html'
});
// 设置静态地址相对目录中间件
app.use(staticFiles('/static/', __dirname + '/static'));
// 设置路由控制器
app.use(controller());

// 错误监听
app.on('error', (err, ctx) => {
    console.log('server error: ', err);
});
app.listen(3000);
console.log('app started with port 3000');